<?php
/**
 * --------------------------------------------------------------
 * 后台首页控制器
 * --------------------------------------------------------------
 * Light Year Doc
 * @author yinq<3331653644@qq.com>
 * --------------------------------------------------------------
 */
namespace app\admin\controller;

use app\common\controller\AdminBase;
use app\admin\model\Admin as AdminModel;
use think\Db;
use think\facade\Cache;

class Index extends AdminBase
{
    /**
     * 后台首页
     */
    public function index()
    {
        $info = Db::query('select VERSION()');
        $system_info = [
            '操作系统'    => PHP_OS,
            '运行环境'    => $_SERVER['SERVER_SOFTWARE'],
            'MYSQL版本'   => $info[0]['VERSION()'],
            '上传附件限制' => ini_get('upload_max_filesize'),
            '执行时间限制' => ini_get('max_execution_time'),
            'curl'        => function_exists("curl_getinfo") ? '是' : '否',
        ];
		
		$data_total = [
		    [
			    'name'    => '手册',
				'icon'    => 'mdi mdi-book-open-outline',
				'bgcolor' => 'bg-primary',
				'total'   => Db::name('manual')->count()
			], [
			    'name'    => '文章',
				'icon'    => 'mdi mdi-file-document-outline',
				'bgcolor' => 'bg-danger',
				'total'   => Db::name('document')->count()
			], [
			    'name'    => '附件',
				'icon'    => 'mdi mdi-attachment',
				'bgcolor' => 'bg-success',
				'total'   => Db::name('attachment')->count()
			], [
			    'name'    => '友链',
				'icon'    => 'mdi mdi-link-variant',
				'bgcolor' => 'bg-purple',
				'total'   => Db::name('friend_links')->count()
			]
		];

        $this->assign([
		    'data_total'  => $data_total,
            'system_info' => $system_info,
            'title'       => '首页'
        ]);

        return $this->fetch();
    }

    /**
     * 清除缓存
     */
    public function clearCache()
    {
        $pathArr = [
            'LOG_PATH'   => env('runtime_path') . 'log/',
            'CACHE_PATH' => env('runtime_path') . 'cache/',
            'TEMP_PATH'  => env('runtime_path'). 'temp/'
        ];
        if (!empty(config('app.site_setting.wipe_cache_type'))) {
            foreach (config('app.site_setting.wipe_cache_type') as $item) {
                if ($item == 'LOG_PATH') {
                    $dirs = (array) glob($pathArr[$item] . '*');
                    foreach ($dirs as $dir) {
                        array_map('unlink', glob($dir . '/*.log'));
                    }
                    array_map('rmdir', $dirs);
                } else {
                    array_map('unlink', glob($pathArr[$item] . '/*.*'));
                }
            }
            Cache::clear(); 
            return $this->success('清除缓存成功');
        } else {
            return $this->error('请在系统设置中悬着需要清除的缓存类型');
        }
    }

    /**
     * 个人信息
     */
    public function profile()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();

            if (isset($data['adminname'])) unset($data['adminname']); // 用户名不允许编辑
            if ($data['id'] != AID) return $this->error('这是个人信息修改，请确保是修改您本人的信息。');

            $result = $this->validate($data, 'Admin.edit');
            if (true !== $result) $this->error($result);

            $res = AdminModel::update($data);
            if ($res) {
                // 重置下session内容
                $admin_auth = session('admin_auth');
                $admin_auth['avatar']   = $data['avatar'];
                $admin_auth['nickname'] = $data['nickname'];
            
                session('admin_auth', $admin_auth);
                session('admin_auth_sign', data_auth_sign($admin_auth));

                $this->success('编辑成功', url('profile'));
            } else {
                return $this->error('编辑失败');
            }
        } else {
            $info = AdminModel::get(AID);

            $this->assign([
                'aid'   => AID,
                'info'  => $info,
                'title' => '个人信息',
            ]);
            return $this->fetch();
        }
    }

    /**
     * 修改登录密码
     */
    public function editPwd()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();

            $result = $this->validate($data, 'Admin.editpwd');
            if (true !== $result) $this->error($result);

            // 验证用户输入的旧密码是否正确
            $ainfo = AdminModel::get(AID);
            if (encrypt_password(sha1($data['oldpassword']), $ainfo['encrypt']) !== $ainfo['password']) {
                return $this->error('您输入的旧密码错误，无法修改密码。');
            }

            $pwdinfo          = encrypt_password(sha1($data['newpassword']));
            $data['encrypt']  = $pwdinfo['encrypt'];
            $data['password'] = $pwdinfo['password'];
            
            unset($data['newpassword']);
            unset($data['oldpassword']);
            unset($data['repassword']);

            $res = AdminModel::update($data);
            if ($res) {
                $this->success('密码修改成功，请重新登录', url('login/logout'));
            } else {
                return $this->error('密码修改失败');
            }
        } else {
            $this->assign([
                'aid'   => AID,
                'title' => '修改密码'
            ]);
            return $this->fetch();
        }
    }
}